/**
 * 消息列表
 */
import { useEffect, useRef } from 'react';
import { useConversation } from '@/context/conversationContext';
import { useAuth } from '@/context/authContext';
import { Avatar } from '@/components/ui/avatar';
import { cn } from '@/lib/utils';

interface Message {
  id: string;
  content: string;
  senderId: string;
  createdAt: string;
  sender: {
    id: string;
    username: string;
    avatar?: string;
  };
}

export default function MessageList() {
  const { currentConversation, messages } = useConversation();
  const { user } = useAuth();
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  if (!currentConversation || !messages) {
    return <div className="flex-1 flex items-center justify-center text-gray-500">
      选择一个对话开始聊天
    </div>;
  }

  return (
    <div className="flex-1 overflow-y-auto p-4 space-y-4">
      {messages.map((message: Message) => {
        const isSelf = message.senderId === user?.id;
        return (
          <div 
            key={message.id}
            className={cn(
              "flex gap-2",
              isSelf ? "flex-row-reverse" : "flex-row"
            )}
          >
            <Avatar 
              className="w-8 h-8"
              src={message.sender.avatar ?? ''}
              alt={message.sender.username}
            />
            <div 
              className={cn(
                "max-w-[70%] px-4 py-2 rounded-2xl",
                isSelf 
                  ? "bg-primary text-primary-foreground" 
                  : "bg-muted"
              )}
            >
              {message.content}
            </div>
          </div>
        );
      })}
      <div ref={messagesEndRef} />
    </div>
  );
}